
var toAgentIndexUrl = rootPath + "s/sys/agent/index.cgi";
var toEditAgentPageUrl = rootPath + "s/sys/agent/edit.cgi";//增加或修改页面

var pageListUrl = rootPath + "s/sys/agent/pagelist";//分页显示
var saveAgentUrl = rootPath + "s/sys/agent/save";//保存
var removeAgentUrl = rootPath + "s/sys/agent/del";//删除
var detailAgentUrl = rootPath + "s/sys/agent/detail";//获取详情
var serverlistUrl = rootPath + "s/sys/server/list";//获取服务器列表（不分页）

function queryList(){
	var results;
    $("#datagrid").datagrid({
//        url : pageListUrl,
        pagination:true,//分页控件
        width : 'auto',// 面板宽度，自动列宽 
        height : 'auto',// 面板高度，自动列高 
        nowrap : false,// :当true时，显示数据在同一行上。默认true。
        checkOnSelect: true,
        rownumbers: true,
        selectOnCheck: true,
        singleSelect:false,
        autoRowHeight:true,
        fitColumns: true,
        pageNo :0,
        pageSize :10,
        queryParams : getQueryParam(),
        loadFilter : function (data) {
            if(data.opStatus == "0"){
            	$("#pageNo").val(data.data.pageNo);
            	$("#pageSize").val(data.data.pageSize);
            	results = data.data.results;
            	var rs ={
            		"rows":	data.data.results,
            		"total":data.data.totalRecord
            	};
                return rs;
                
            }
        },
        columns : [ [  {
            field:'_',
            checkbox:true,
            width:'5%'
        },{
            field : 'agentName',
            title : '代理商名称',
            width : '15%',
            align : 'center',
            sortable : true
        }, {
            field : 'serverName',
            title : '服务器名称',
            width : '10%',
            align : 'center',
            formatter: function(value,row){
        		var result = "";
        		if(row.areaSever != undefined){
        			result = row.areaSever.serverName;
        		}
        		return result;
            },
            sortable : true
        }, {
            field : 'identity',
            title : '身份标识',
            width : '15%',
            align : 'center',
            sortable : true
        },  {
            field : 'account',
            title : '账号',
            align : 'center',
            width : '10%',
            sortable : true
        }, {
            field : 'phoneNumber',
            title : '联系电话',
            width : '15%',
            align : 'center',
            sortable : true,
        },{
            field : 'address',
            title : '联系地址',
            width :'20%',
            align : 'center',
            sortable : true
        },{
            field : 'agentId',
            title : '操作',
            width :'15%',
            align : 'center',
            formatter: function(value,row){
            		var result = "";
            		result += '<button class="btn btn-default btn-xs" type="button" onclick="toEditAgentPage(\''+value+'\')"><i class="glyphicon glyphicon-pencil"></i> 修改 </button>';
            		return result;
            },
            sortable : true
        }] ],
        onDblClickRow : function(index,row){
        }
    });
}

//获取表单参数
function getQueryParam() {
	var pageNo;
	var pageNoStr = $("#pageNo").val();
	if(pageNoStr && pageNoStr != ""){
		pageNo = parseInt(pageNoStr);
	}
	var pageSize;
	var pageSizeStr = $("#pageSize").val();
	if(pageSizeStr && pageSizeStr != ""){
		pageSizeStr = parseInt(pageSizeStr);
	}
	
	var param = {
    		pageNo : pageNo,
    		pageSize : pageSize,
    		"PublishAgentEntity.agentName" : $("#agentName").val(),
            "PublishAgentEntity.account" : $("#account").val(),
            "PublishAgentEntity.phoneNumber" : $("#phoneNumber").val(),
            "PublishAgentEntity.identity" : $("#identity").val(),
            "PublishAgentEntity.areaSever.serverName" : $("#serverName").val(),
    };
    return param;
	
}

//刷新
function refreshGrid(){
	 $("#datagrid").datagrid("reload",getQueryParam());
}

//批量删除服务器的方法
function removeAgent(agentIds) {
    var idsStr = agentIds.join(",");
    $.ajax({
        url : removeAgentUrl,
        type : 'post',
        data :{ids :idsStr},
        success : function (res) {
            if(res.opStatus == "0"){
                showTip(res.msgDesc,1000,function () {
                	refreshGrid();
                });
            }else {
                showMsg(res.msgDesc);
            }
        }
    })
};

//保存服务器
function saveAgent() {
	
	var valiMsg = validate();//验证表单信息
    if(valiMsg != ""){
       showMsg(valiMsg);
        return;
    }
	
	var param = {
		
		"PublishAgentEntity.agentId" : $("#edit_agentId").val(),
		"PublishAgentEntity.agentName" : $("#edit_agentName").val(),
		"PublishAgentEntity.identity" : $("#edit_identity").val(),
		"PublishAgentEntity.account" : $("#edit_account").val(),
		"PublishAgentEntity.password" : $("#edit_password").val(),
		"PublishAgentEntity.phoneNumber" : $("#edit_phoneNumber").val(),
		"PublishAgentEntity.address" : $("#edit_address").val(),
		"PublishAgentEntity.areaSever.serverId" : $("#edit_serverId").val(),
	}
	$.ajax({
        url : saveAgentUrl,
        type : 'post',
        data :param,
        success :function (res) {
        	if(res.opStatus == "0"){
        	 showTip(res.msgDesc,1000,function () {
                 $("#editModal").modal("hide");

                 refreshGrid();
             });
        	}else {
              showMsg(res.msgDesc);
        	}
        }
    });
}

// 将服务器列表加入选择框中
function appendServerListToSelect(serverId){
	$.ajax(
			{
				url : serverlistUrl,
				
				success :function (res) {
					if( res.opStatus == "0"){
						var serverArr = res.data;
						$(serverArr).each(function(i,obj){
							var html = "";
							if(obj.serverId == serverId){
								html = "<option value=\""+obj.serverId+"\" selected>"+obj.serverName+"</option>";
							}else {
								html = "<option value=\""+obj.serverId+"\">"+obj.serverName+"</option>";
							}
							
							$("#edit_serverId").append(html);
						});
					}
				}
			}
	)
}

//转到编辑页面（修改或增加）
function toEditAgentPage(agentId){
	

	if(agentId && agentId != ""){
		//修改
		$("#edit-modal").load(toEditAgentPageUrl + "?agentId=" + agentId,{_: Math.random()},function () {
			 $.ajax({
		            url : detailAgentUrl,
		            type : 'post',
		            data :{'id' : agentId},
		            success :function (res) {
			               if( res.opStatus == "0"){
			            	   $("#edit_agentId").val(res.data.agentId);
			            	   $("#edit_agentName").val(res.data.agentName);
			            	   $("#edit_identity").val(res.data.identity);
			            	   $("#edit_account").val(res.data.account);
			            	   $("#edit_password").val(res.data.password);
			            	   $("#edit_phoneNumber").val(res.data.phoneNumber);
			            	   $("#edit_address").val(res.data.address);
//			            	   $("#edit_serverName").val(res.data.areaSever.serverName);
			            	   var serverId = res.data.areaSever.serverId;
//			            	   $("#edit_serverId").children("option[value="+serverId+"]").attr("selected");
			            	   appendServerListToSelect(serverId)
			            	   //服务器名称和代理商账号不能修改
			            	   $("#edit_serverId").attr("disabled","disabled");
			            	   $("#edit_account").attr("readonly","readonly");
			               }else {
			            	   showMsg(res.msgDesc);
			               }
			               $('#editModalLabel').html("修改");
			               $('#editModal').modal('show');
			               
		                }
		        });
		    });
	}else {//添加
		$("#edit-modal").load(toEditAgentPageUrl,{_: Math.random()},function () {
			appendServerListToSelect()
			 $('#editModal').modal('show');
		});
		
	}
}

//验证表单信息
function validate(){
	var msg = "";
	//必填项的自定义属性 require 为 true,获取这些 input ,如果所填内容为空，则显示提示信息（data-message属性）
	var inputs = $("#agentEdit input[require='true']");
	var err = checkEmpty(inputs);
	debugger;
	$(err).each(function(){
		msg += $(this).attr("data-message")+"</br>";
	});
	
	var phoneNumber = $("#edit_phoneNumber").val();//电话号码
	if(!(/^1[34578]\d{9}$/.test(phoneNumber))){
    	msg += "手机号码(11位数字，以13/14/15/17/18开头)"+"</br>";
    }
	
	return msg;
}

$(document).ready(function () {
	queryList();// 加载分页数据
	
	$("#search_button").on("click",function () {
		refreshGrid();
    });
	
	$("#remove_button").on("click",function () {
    	var rows = $("#datagrid").datagrid("getChecked");
        if(rows.length > 0){
            showConfirm("是否确认删除？",function () {
                var agentIds = [];
                for(var i in rows ){
                	agentIds.push(rows[i].agentId);
                }
                removeAgent(agentIds);
            });
        }else {
            showMsg("请选择要删除的代理商！");
        }
		
	});
	
	$("#add_button").on("click",function(){
		toEditAgentPage("");
	});
	
	var rows = $("#datagrid").datagrid("getPager");
	 $("#datagrid").datagrid({
		url : pageListUrl,
        onBeforeLoad:function(param){
            param.pageSize = param.rows;
            param.pageNo = param.page;
            param.rows = null;
            param.page = null;
        }
    }); 
	
});

